home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part2 / 15336 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.6 KB

  1. Path: user2.mnsinc.com!huang
  2. From: huang@mnsinc.com (Szu-Wen Huang)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: char* still alive after free ???
  5. Date: 18 Apr 1996 15:09:43 GMT
  6. Organization: Monumental Network Systems
  7. Message-ID: <4l5lvn$1s4@news1.mnsinc.com>
  8. References: <317269EA.11BB93C2@studbox.uni-stuttgart.de>
  9. NNTP-Posting-Host: user.mnsinc.com
  10. X-Newsreader: TIN [version 1.2 PL2]
  11.  
  12. Markus Heller (Markus.Heller@studbox.uni-stuttgart.de) wrote:
  13.  
  14. : I want to use it to store different "strings" (at diffreent times).
  15. : E.g., if I want to sore 10 characters in text, I do a 
  16. : text=(char *) malloc(10*sizeof(char));
  17. : When I want to use text to store 3 other characters, I first do a
  18. : free(text); text=NULL; and finally a
  19. : text=(char *) malloc(3*sizeof(char));
  20. : But to my surprise there are still the 4thh to 10th charcter of
  21. : text contained before the free(text)/malloc... ???
  22. : This happens under linux, but why ?
  23. : (what I want to to is to get filenames from the user and then open those
  24. :  files by a function to which I pass the file name..)
  25.  
  26. This is not surprising.  free() updates some internal data structure
  27. to tell itself that the memory allocated for text (the 10 chars) is
  28. now free for use, but *does not* erase its contents.  The subsequent
  29. malloc() was given the same chunk of memory that was previously freed,
  30. so its contents are still there.  This makes perfect sense because
  31. otherwise free() would be wasting its time clearing memory.  If you
  32. needed a cleared (to zero) memory space, use calloc() instead.
  33.  
  34. By the way, the "text = NULL;" is useless, because its value is
  35. immediately overwritten by the subsequent malloc().
  36.